﻿using System;
using Ease.EaseNode.Runtime;
using Ease.EaseNode.Runtime.Param;

namespace Ease.EaseMission.Runtime
{
    public class MissionDataHandler : IMissionStageAgent
    {
        public IEaseNodeData Data { get; set; }
        private RunState currentState;

        public RunState CurrentState
        {
            get => currentState;
            set
            {
                if (currentState != value)
                {
                    OnRunStateChange?.Invoke(value);
                    OnValueChangeEvent?.Invoke(new StateChangeParam() {newState = (NodeState) value});
                }

                currentState = value;
            }
        }

        public event Action<RunState> OnRunStateChange;

        private MissionData missionData;
        private IMissionAgent agent;

        public MissionDataHandler(IEaseNodeData data)
        {
            Data = data;
            missionData = Data as MissionData;
        }

        public void Start()
        {
            //等待行为执行完毕。
            if (agent == null)
                agent = missionData.Param.CreateAgent();
            agent.OnRunStateChange -= OnStateChange;
            agent.OnRunStateChange += OnStateChange;
            agent.Start();
        }

        public void Reset()
        {
            CurrentState = RunState.NONE;
            agent.Reset();
        }

        public event Action<BaseChangeParam> OnValueChangeEvent;
        
        private void OnStateChange(RunState newRunState)
        {
            CurrentState = newRunState;
            if (CurrentState == RunState.FINISH)
            {
                agent.OnRunStateChange -= OnStateChange;
            }
        }
    }
}